package com.edan.partnerback.service.impl.Task;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.edan.partnerback.common.VO.DynamicCache;
import com.edan.partnerback.entity.Dynamic;
import com.edan.partnerback.service.IDynamicService;
import com.edan.partnerback.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author 86159
 * @description 定时任务，用于保证redis的连接正常
 * @create 2023/12/19 14:37
 */
@Service
@Slf4j
public class endTask {
    @Resource
    RedisCache redisCache;
    @Resource
    IDynamicService dynamicService;
    //每9分钟连接一次数据库
    @Scheduled(cron = "0 0/9 * * * ?")
    private void redisReconnection(){
        RedisCache.ping();
    }

    /**
     * 每天每一小时更新一次持久化redis中的动态浏览量到数据库中
     */
    @Scheduled(cron = "0 0 * * * ?")
    private void dynamicViewTask(){
        log.info("dynamic task");
        //从redis中获取动态的浏览量
        Set<ZSetOperations.TypedTuple<Integer>> dynamicViews = redisCache.getCacheZSet(DynamicCache.DYNAMICVIEW);
        dynamicViews.forEach(dynamicViewsTuple -> dynamicService.update(new UpdateWrapper<Dynamic>().set("views", dynamicViewsTuple.getValue())
                .eq("id", dynamicViewsTuple.getValue())));
    }
}
